package com.dries.security.core.social.qq.connect;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/16 11:24
 */
@Slf4j
public class QQOAuth2Template extends OAuth2Template {

    public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {

        String responseStr = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);

        log.info("获取accessToken的响应：" + responseStr);
        // String[] items1 = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr,"&");
        // String accessToken = StringUtils.substringAfterLast(items[0], "=");
        // Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
        // String refreshToken = StringUtils.substringAfterLast(items[2], "=");
        String[] items = StrUtil.split(responseStr,"&");
        String accessToken = StrUtil.subAfter(items[0], "=", false);
        Long expiresIn = new Long(StrUtil.subAfter(items[1], "=", false));
        String refreshToken = StrUtil.subAfter(items[2], "=", false);

        return new AccessGrant(accessToken, null, refreshToken, expiresIn);
    }

    @Override
    protected RestTemplate createRestTemplate() {

        RestTemplate restTemplate = super.createRestTemplate();
        restTemplate.getMessageConverters()
                .add(new StringHttpMessageConverter(StandardCharsets.UTF_8));

        return restTemplate;
    }
}
